<template>
	<view class="customer-list-page">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<uni-icons type="search" color="#999" size="24"></uni-icons>
			<input v-model="searchKeyword" placeholder="搜索客户名称/电话" @input="handleSearch" />
		</view>

		<!-- 全选与数量统计（仅多选模式） -->
		<view class="select-controls" v-if="selectMode == 'multiple'">
			<view class="select-all" @click="toggleSelectAll">
				<checkbox color="#e60012" :checked="isSelectAll"></checkbox>
				<text class="select-text">全选</text>
			</view>
			<view class="selected-count">
				<text>已选 {{ selectedIds.length }} 人</text>
			</view>
		</view>

		<!-- 客户列表：关键修改：用 checkbox-group 绑定 v-model -->
		<scroll-view class="customer-scroll" scroll-y @scrolltolower="loadMore">
			<view class="customer-list">
				<!-- 必须用 checkbox-group 包裹，v-model 绑定选中的 ID 数组 -->
				<checkbox-group v-model="selectedIds" @change="handleGroupChange">
					<view class="customer-item" v-for="(item, index) in filteredCustomers" :key="item.id"
						:class="{ 'selected': isItemSelected(item.id) }" @click="toggleItemSelect(item.id)">
						<!-- checkbox：value 绑定客户 ID，无需单独绑定 checked -->
						<view class="product-options">
							<label class="option-item">
								<checkbox color="#e60012" :value="item.id + ''" :checked="isItemSelected(item.id)">
								</checkbox>
							</label>
						</view>

						<!-- 客户信息 -->
						<image class="customer-avatar" :src="item.avatar || '/static/default-avatar.png'"></image>
						<view class="customer-info">
							<text class="customer-name">{{ item.cname || item.name }}</text> <!-- 兼容接口返回的字段名 -->
							<view class="customer-meta">
								<text class="customer-phone"
									v-if="item.mobile || item.phone">{{ item.mobile || item.phone }}</text>
								<text class="customer-tag"
									v-if="item.biaoqian || item.tag">{{ item.biaoqian || item.tag }}</text>
							</view>
						</view>

						<!-- 操作图标 -->
				<!-- 		<view class="action-area">
							<view class="action-icon" @click.stop="sendSms(item)">
								<uni-icons type="chatbubble" color="#fff" size="22"></uni-icons>
							</view>
							<view class="action-icon" @click.stop="makeCall(item)">
								<uni-icons type="phone" color="#fff" size="22"></uni-icons>
							</view>
						</view> -->
					</view>
				</checkbox-group>
			</view>

			<!-- 加载更多/空状态 -->
			<view class="load-more" v-if="showLoadMore">
				<uni-icons type="circle" size="24" v-if="loading"></uni-icons>
				<text v-else-if="hasMore">上拉加载更多</text>
				<text v-else>已加载全部</text>
			</view>
			<view class="empty-state" v-if="filteredCustomers.length == 0 && !loading">
				<uni-icons type="contact" color="#ccc" size="60"></uni-icons>
				<text class="empty-text">暂无匹配的客户</text>
			</view>
		</scroll-view>

		<!-- 导入按钮 -->
		<view class="p-t-b-24">
			<button class="import-btn" :disabled="selectMode == 'single' ? !singleSelectedId : selectedIds.length == 0"
				@click="importSelected">
				{{ selectMode == 'single' ? '导入选中客户' : `导入选中的 ${selectedIds.length} 人` }}
			</button>
		</view>
	</view>
</template>

<script>
	import {
		cinfoList,
		addGoodStartCustomer
	} from '@/common/api/renwu.js'
	export default {
		data() {
			return {
				searchKeyword: '',
				selectMode: 'multiple', // single/multiple
				singleSelectedId: null, // 单选选中的ID
				selectedIds: [], // 多选选中的ID数组（关键：绑定checkbox-group）
				isSelectAll: false,
				customers: [],
				page: 1,
				pageSize: 10,
				total: 0, // 从接口获取真实总数，避免模拟值导致加载异常
				loading: false,
				hasMore: true,
				showLoadMore: false,
				task_id: null
			};
		},
		computed: {
			// 筛选后的客户列表
			filteredCustomers() {
				if (!this.searchKeyword) return this.customers;
				const keyword = this.searchKeyword.trim().toLowerCase();
				return this.customers.filter(item => {
					const name = (item.cname || item.name)?.toLowerCase() || '';
					const phone = (item.mobile || item.phone) || '';
					const tag = (item.biaoqian || item.tag)?.toLowerCase() || '';
					return name.includes(keyword) || phone.includes(keyword) || tag.includes(keyword);
				});
			}
		},
		onLoad(options) {
			this.task_id = options.task_id
			this.loadData();
		},
		methods: {
			// 加载数据：从接口获取真实数据，更新total
			loadData(searchKeyword) {
				if (this.loading || !this.hasMore) return;
				this.loading = true;
				let params = {
					pageNum: this.page,
					pageSize: this.pageSize
				}
				if (searchKeyword) {
					let isNum = /^\d+$/.test(searchKeyword);
					if (isNum) {
						params.mobile = searchKeyword;
					} else {
						params.cname = searchKeyword;
					}
				}
				cinfoList(params).then(res => {
					if (res.code == 200 && res.rows) { // 适配接口返回格式
						const newData = res.rows.map(item => ({
							...item,
							// 统一字段名（避免接口返回字段不一致）
							name: item.cname || item.name,
							phone: item.mobile || item.phone,
							tag: item.biaoqian || item.tag
						}));
						this.customers = [...this.customers, ...newData];
						this.total = res.total || 0; // 从接口获取真实总数
						this.page++;

						// 判断是否还有更多数据（真实逻辑：当前条数 < 总条数）
						this.hasMore = this.customers.length < this.total;
					} else {
						this.hasMore = false;
					}
					this.loading = false;
					this.showLoadMore = true;
				}).catch(err => {
					console.error('加载客户失败：', err);
					this.loading = false;
					this.hasMore = false;
				});
			},

			// 触底加载更多
			loadMore() {
				if (this.searchKeyword) return;
				this.loadData();
			},

			// 搜索处理：修复模拟数据与接口字段一致
			handleSearch() {
				// 清除上一次的计时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}
				this.page = 1;
				this.customers = [];
				this.hasMore = true;
				this.selectedIds = []; // 搜索时重置选中状态
				this.singleSelectedId = null;

				// 300ms 后执行搜索（用户停止输入 300ms 才触发）
				this.searchTimer = setTimeout(() => {
					this.loadData(this.searchKeyword);
				}, 300); // 节流时间：300ms（可根据需求调整）
			},

			// 获取随机标签


			// 判断单个客户是否选中（用于高亮行）
			isItemSelected(id) {
				if (this.selectMode == 'single') {
					return this.singleSelectedId == id;
				}
				return this.selectedIds.includes(id + ''); // 注意：v-model 绑定的是字符串，需转义
			},

			// 点击行切换选中状态
			toggleItemSelect(id) {
				const idStr = id + '';
				if (this.selectMode == 'single') {
					this.singleSelectedId = this.singleSelectedId == id ? null : id;
				} else {
					// 切换多选数组中的ID
					const index = this.selectedIds.indexOf(idStr);
					if (index > -1) {
						this.selectedIds.splice(index, 1);
					} else {
						this.selectedIds.push(idStr);
					}
				}
			},

			// checkbox-group 状态变化时同步全选
			handleGroupChange() {
				if (this.selectMode !== 'multiple') return;
				// 全选状态：选中的ID数 == 客户总数
				this.isSelectAll = this.selectedIds.length == this.customers.length;

			},

			// 全选/取消全选
			toggleSelectAll() {
				if (this.selectMode !== 'multiple' || this.customers.length == 0) return;

				const newSelectAllState = !this.isSelectAll;
				this.isSelectAll = newSelectAllState;

				if (newSelectAllState) {
					// 全选：将所有客户ID转为字符串，加入 selectedIds
					this.selectedIds = this.customers.map(item => item.id + '');
				} else {
					// 取消全选：清空数组
					this.selectedIds = [];
				}
			},

			// 导入选中客户：回传数据给上一页
			importSelected() {
				let selectedData;

				// 1. 获取选中的客户数据
				if (this.selectMode == 'single') {
					selectedData = this.customers.find(item => item.id == this.singleSelectedId);
					if (!selectedData) {
						uni.showToast({
							title: '请选择客户',
							icon: 'none'
						});
						return;
					}
					selectedData = [selectedData]; // 统一为数组格式
				} else {
					// 多选：根据selectedIds筛选客户（注意ID转字符串匹配）
					selectedData = this.customers.filter(item =>
						this.selectedIds.includes(item.id + '')
					);
					if (selectedData.length == 0) {
						uni.showToast({
							title: '请至少选择一个客户',
							icon: 'none'
						});
						return;
					}
				}
				console.log(selectedData, '---选择人员');


				const transformedArr = this.selectedIds.map(item => ({
					customerId: Number(item), // 将字符串转为数字类型的id
					tasksId: this.task_id
				}));
				// 3. 提示并返回上一页
				uni.showLoading({
					title: '导入中...'
				});
				try {
					addGoodStartCustomer(transformedArr).then(res => {
						console.log(res, '-----导入成功')
						uni.hideLoading();
						uni.showToast({
							title: '导入成功',
							icon: 'success'
						});
						// 2. 获取事件通道（与上一页通信）
						const eventChannel = this.getOpenerEventChannel();

						// 3. 触发上一页的 refreshData 事件（通知上一页更新数据）
						eventChannel.emit('refreshData');
						// 延迟返回，确保提示可见
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							}); // 必须用 navigateBack 返回
						}, 1000);
					})
				} catch (error) {
					uni.hideLoading();
					//TODO handle the exception
					uni.showToast({
						title: error,
						icon: 'none'
					});
				}
			},

			// 重置选择状态
			resetSelection() {
				this.singleSelectedId = null;
				this.selectedIds = [];
				this.isSelectAll = false;
			},

			// 更多操作（保留）
			handleMore() {
				uni.showActionSheet({
					itemList: ['批量删除', '导出列表', '刷新数据'],
					success: (res) => {
						if (res.tapIndex == 2) {
							this.resetSelection();
							this.page = 1;
							this.customers = [];
							this.hasMore = true;
							this.loadData();
						}
					}
				});
			},

			// 短信/电话功能（占位，可根据需求实现）
			sendSms(item) {
				uni.showToast({
					title: `发送短信给${item.cname}`,
					icon: 'none'
				});
			},
			makeCall(item) {
				uni.makePhoneCall({
					phoneNumber: item.mobile || item.phone
				});
			}
		}
	};
</script>

<style scoped>
	/* 样式保持不变，如需优化可调整以下几点： */
	.customer-list-page {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		background-color: #f5f5f5;
		position: relative;
	}

	.search-bar {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 40rpx;
		padding: 12rpx 24rpx;
		margin: 20rpx 32rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.search-bar input {
		flex: 1;
		font-size: 26rpx;
		padding: 0 12rpx;
		color: #333;
		height: 44rpx;
		/* 固定高度，避免输入时变形 */
	}

	.select-controls {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 32rpx;
		background-color: #fff;
	}

	.select-all {
		display: flex;
		align-items: center;
	}

	.select-text {
		font-size: 26rpx;
		color: #333;
		margin-left: 12rpx;
	}

	.selected-count {
		font-size: 24rpx;
		color: #e60012;
	}

	.customer-scroll {
		width: 100%;
		/* 关键：减去顶部搜索栏、底部按钮等固定高度，确保滚动区域可见 */
		height: calc(100vh - 320rpx);
		/* 补充：添加overflow确保内容溢出时可滚动 */
		overflow-y: auto;
	}

	.customer-list {
		background-color: #fff;
	}

	.customer-item {
		display: flex;
		align-items: center;
		padding: 24rpx 32rpx;
		border-bottom: 2rpx solid #f5f5f5;
		transition: background-color 0.2s;
	}

	.customer-item.selected {
		background-color: #fff5f5;
	}

	.product-options {
		margin-right: 24rpx;
		/* 给选择框留空间 */
	}

	.customer-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 24rpx;
		background-color: #f5f5f5;
	}

	.customer-info {
		flex: 1;
		overflow: hidden;
	}

	.customer-name {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		display: block;
		margin-bottom: 8rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		/* 避免名称过长换行 */
	}

	.customer-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.customer-phone,
	.customer-tag {
		font-size: 24rpx;
		color: #666;
		white-space: nowrap;
	}

	.customer-tag {
		padding: 2rpx 12rpx;
		background-color: #f5f5f5;
		border-radius: 14rpx;
	}

	.action-area {
		width: 140rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.action-icon {
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
	}

	.action-icon .uni-icons {
		background-color: #007AFF;
		border-radius: 50%;
		padding: 8rpx;
		box-sizing: border-box;
	}

	.load-more {
		padding: 30rpx 0;
		text-align: center;
		font-size: 24rpx;
		color: #999;
		background-color: #fff;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		background-color: #fff;
	}

	.empty-text {
		font-size: 26rpx;
		color: #999;
		margin-top: 20rpx;
	}

	.import-btn {
		background-color: #e60012;
		color: #fff;
		font-size: 28rpx;
		width: 680rpx;
		height: 88rpx;
		line-height: 88rpx;
		margin: 0 auto;
		border-radius: 44rpx;
		position: fixed;
		/* 固定在底部，避免滚动时消失 */
		left: 0;
		right: 0;
		bottom: 35rpx;
	}

	.import-btn:disabled {
		background-color: #ffb8b8;
		color: #fff;
	}
</style>